package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.AsyncDimFunction_lj;
import com.atguigu.bean.TradeProvinceOrderWindow;
import com.atguigu.util.ClickHouseUtil_lj;
import com.atguigu.util.DateFormatUtil_lj;
import com.atguigu.util.MyKafkaUtil_lj;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author 晶晶  1.4.2  各省份交易统计  搞定
 * @Date 2023 03 28 01 05
 **/
public class Dws_TradeProvinceOrderWindow {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        String topic = "dwd_trade_order_detail_aa";
        String groupId = "dws_trade_province_order_window_0926";
        DataStreamSource<String> kafkaDs = env.addSource(MyKafkaUtil_lj.getFinkKafkaConsumer(topic, groupId));

        //kafkaDs.print("》》》》》》》》》》》》》》》》》");
        SingleOutputStreamOperator<JSONObject> jsonDs = kafkaDs.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null  ) {
                    JSONObject jsonObject = JSON.parseObject(value);

                    if (jsonObject.getString("user_id")!=null){
                        out.collect(jsonObject);
                    }

                }
            }
        });

        //提取时间戳 获得watermark
        SingleOutputStreamOperator<JSONObject> dsWithWM = jsonDs.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        //System.out.println(element.getLong("create_time"));
                        return element.getLong("create_time");
                    }
                }));

        KeyedStream<JSONObject, String> keyedByUserId = dsWithWM.keyBy(line -> line.getString("user_id"));

        //转换为javabean
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanDs = keyedByUserId.flatMap(new RichFlatMapFunction<JSONObject, TradeProvinceOrderWindow>() {

            private ValueState<String> lastState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig stateTTL = new StateTtlConfig.Builder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite).build();
                ValueStateDescriptor<String> stateProperties = new ValueStateDescriptor<>("last-state", String.class);
                stateProperties.enableTimeToLive(stateTTL);

                lastState = getRuntimeContext().getState(stateProperties);
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeProvinceOrderWindow> out) throws Exception {
                String lastValue = lastState.value();
                //按user_id分组 若状态为null,状态更新为1
                long userCn = 0L;
                if (lastValue==null){
                    lastState.update("1");
                    userCn=1L;
            }

                    out.collect(TradeProvinceOrderWindow.builder()
                            .orderAmount(value.getBigDecimal("final_amount"))
                            .orderUserIdCount(userCn)
                            .orderCount(1L)
                            .provinceId(value.getString("province_id"))
                            .build());
                }

        });

        //beanDs.print(">>>>>>>>>>>>>>>>>>>>>>>");

        //根据province_id分组开窗 聚合
        SingleOutputStreamOperator<TradeProvinceOrderWindow> resultDs = beanDs.keyBy((KeySelector<TradeProvinceOrderWindow, String>) TradeProvinceOrderWindow::getProvinceId)

                .window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<TradeProvinceOrderWindow>() {
                            @Override
                            public TradeProvinceOrderWindow reduce(TradeProvinceOrderWindow value1, TradeProvinceOrderWindow value2) throws Exception {
                                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                                value1.setOrderUserIdCount(value1.getOrderUserIdCount()+value2.getOrderUserIdCount());
                                value1.setOrderCount(value1.getOrderCount()+value2.getOrderCount());
                                //System.out.println(value1);
                                return value1;
                            }
                        },

                        new WindowFunction<TradeProvinceOrderWindow, TradeProvinceOrderWindow, String, TimeWindow>() {
                            @Override
                            public void apply(String s, TimeWindow window, Iterable<TradeProvinceOrderWindow> input, Collector<TradeProvinceOrderWindow> out) throws Exception {
                                TradeProvinceOrderWindow next = input.iterator().next();
                                next.setStt(DateFormatUtil_lj.toYmdHms(window.getStart()));
                                next.setEdt(DateFormatUtil_lj.toYmdHms(window.getEnd()));
                                next.setTs(System.currentTimeMillis());
                                //System.out.println(next);
                                out.collect(next);
                            }
                        });

        //resultDs.print(">>>>>>>>>>>>>>>>");

        //补充维度字段
        SingleOutputStreamOperator<TradeProvinceOrderWindow> lastDs = AsyncDataStream.unorderedWait(resultDs, new AsyncDimFunction_lj<TradeProvinceOrderWindow>("dim_base_province".toUpperCase()) {
            @Override
            public String getKey(TradeProvinceOrderWindow input) {
                return input.getProvinceId();
            }

            @Override
            public void join(TradeProvinceOrderWindow input, JSONObject dimInfo) {
                input.setProvinceName(dimInfo.getString("name".toUpperCase()));
            }


        }, 60, TimeUnit.SECONDS);

        //写入clickhouse
        //lastDs.print(">>>>>>>>>>>>>>>");
        lastDs.addSink(ClickHouseUtil_lj.getClickHouseSink("insert into dws_trade_province_order_window values(?,?,?,?,?,?,?,?)"));

        //运行程序
        env.execute("DwsTradeProvinceOrderWindow");

    }
}
